  let model =require('../model/model')
  let encryption=require('../tool/encryption')
  let CryptoJS=require('crypto-js')
  let time=require('../tool/gettime')
  let fs =require('fs')
  function checkuser(req,res,next){
    let freePath=['/login','/logon','/register','/registerOn',"/confir"];
    // console.log('经过use'+req.session.userInfo)
   
    if(freePath.includes(req.path)){
        if(req.session.userInfo){
            res.redirect("/")
            return
        } 

                next();
    }else if( req.session.userInfo){      
        let check= JSON.parse(req.session.userInfo)
        let Private=check.password;
        if(check.password.length<32){
         Private= CryptoJS.MD5(`${check.password}${encryption}`).toString();
        } 
        let sql=`SELECT * FROM userinfo WHERE username=? and password =?`
        let bind =[check.username,Private]
        model(sql,bind)
        .then(rows=>{
            if(!rows[0]){
              
                console.log("有信息通过,验证失败"+req.session.userInfo)
                req.session.destroy()
                    res.redirect('/login')
                // res.send("flas")
             }else{
                req.session.userInfo=JSON.stringify(rows[0])
                if(check.password.length<32){
                    let nowtime=time.nowtime()
                    console.log(nowtime)
                    let sql2=`UPDATE userinfo SET last_login=${nowtime} WHERE user_id=${rows[0].user_id}`
                    model(sql2).then(result=>console.log("修改登录时间成功"+result.affectedRows)).catch(err=>{
                        console.log("修改登录时间失败:"+err)
                        result
                    })
                }
                let ti= new Date()
                let data=`用户:${rows[0].username}----${req.connection.remoteAddress ||req.headers['x-forwarded-for']}-进入了${req.url}
                ${ti.getFullYear()}-${ti.getMonth()+1}-${ti.getDate()}-${ti.getHours()}:${ti.getMinutes()}:${ti.getSeconds()}\n`
                console.log(data)
                fs.appendFileSync('./error.log',data)
                next();
             }
        })
    }else{
        

     //"没有info打回去
        res.redirect('/login')
    }

}
module.exports=checkuser;